/**
 * 
 */
package ro.dta.idbi.model;

import java.awt.BasicStroke;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.filechooser.FileFilter;

import org.jibble.epsgraphics.EpsGraphics2D;

import ro.dta.idbi.interfaces.ISaveStrategy;

import com.mxgraph.io.mxCodec;
import com.mxgraph.swing.mxGraphComponent;

/**
 * EPS save strategy, used to save a graph as a EPS file
 * 
 * @author Tudor Dobrila
 * 
 */
public class SaveStrategyEps implements ISaveStrategy {

	@Override
	public String getExtension() {
		return ".eps";
	}

	@Override
	public FileFilter getFileFilter() {
		return new EpsFilter();
	}

	@Override
	public void save(mxGraphComponent graphComponent, mxCodec codec, String path) throws FileNotFoundException, IOException {
		EpsGraphics2D graphics = new EpsGraphics2D("", new FileOutputStream(path), 0, 0,
				graphComponent.getPreferredSize().width, graphComponent.getPreferredSize().height);
		graphComponent.paint(graphics);
		graphics.setColor(Color.WHITE);
		graphics.setStroke(new BasicStroke(1));
		graphics.drawLine(0, 0, graphComponent.getPreferredSize().width, 0);
		graphics.drawLine(0, 0, 0, graphComponent.getPreferredSize().height);
		graphics.close();
	}

	/**
	 * Filter used to show only EPS files in the JFileChooser
	 * 
	 * @author Tudor Dobrila
	 * 
	 */
	static class EpsFilter extends FileFilter {

		@Override
		public boolean accept(final File file) {
			boolean result = false;
			if (file.isDirectory()) {
				result = true;
			} else {
				final int dotPos = file.getName().lastIndexOf(".");
				if (dotPos != -1) {
					final String extension = file.getName().substring(dotPos).toLowerCase();

					if (".eps".equals(extension)) {
						result = true;
					}
				}
			}

			return result;
		}

		@Override
		public String getDescription() {
			return "EPS files (.eps)";
		}

	}

}
